﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace ETHotfix
{


    public class SaveComponent : Component
    {
        public int score;


        /// <summary>
        /// 新游戏
        /// </summary>
        public void NewGame()
        {
            score = 0;
            JSONSave();
        }

        /// <summary>
        /// 继续游戏
        /// </summary>
        public void ContinueGame()
        {
            SaveInfo save = JSONLoad();

            score = save.score;
        }

        /// <summary>
        /// 保存SaveInfo
        /// </summary>
        /// <returns></returns>
        private SaveInfo CreateSaveObject()
        {
            SaveInfo save = new SaveInfo();
            save.score = score;
            return save;
        }

        /// <summary>
        /// 保存数据到文件
        /// </summary>
        public void JSONSave()
        {
            SaveInfo save = CreateSaveObject();
            string filePath = Application.dataPath + "/Res/JsonData" + "/GameDataJSON.json";
            //将对象转化为字符串
            string jsonStr = JsonHelper.ToJson(save);
            Log.Debug(jsonStr);
            //将转换过后的json字符串写入json文件
            StreamWriter writer = new StreamWriter(filePath);
            writer.Write(jsonStr);//写入文件
            writer.Close();
            AssetDatabase.Refresh();
        }

        /// <summary>
        /// 加载文件到数据
        /// </summary>
        /// <returns></returns>
        public SaveInfo JSONLoad()
        {
            string filePath = Application.dataPath + "/Res/JsonData" + "/GameDataJSON.json";
            //读取文件
            StreamReader reader = new StreamReader(filePath);
            string jsonStr = reader.ReadToEnd();
            reader.Close();
            //Debug.Log(jsonStr);
            //字符串转换为save对象
            SaveInfo data = JsonHelper.FromJson<SaveInfo>(jsonStr);
            return data;
        }

        public override void Dispose()
        {
            if (this.IsDisposed)
            {
                return;
            }
            JSONSave();
            base.Dispose();
        }
    }

}